package com.qfedu.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * 创建者: QF-SUN
 * 创建时间: 2023/3/27 11:16
 * 描述:
 */
//@WebListener
public class MySessionListener implements HttpSessionListener {
    //对象已创建
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
//        httpSessionEvent //session 事件
        HttpSession session = httpSessionEvent.getSession();
        //获取 (全局) ServletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取count值， 加一，再存储
        Object count = servletContext.getAttribute("count");
        if(count == null){
            servletContext.setAttribute("count", 1);
        }else {
            Integer c = (Integer) count;
            servletContext.setAttribute("count", ++ c );
        }
        System.out.println("有一位新用户上线了......");
    }
    // 对象已销毁
    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        System.out.println("有一位新用户下线了......");
        //httpSessionEvent //session 事件
        HttpSession session = httpSessionEvent.getSession();
        //获取 (全局) ServletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取count值， 加一，再存储
        Object count = servletContext.getAttribute("count");
        if(count == null){
            servletContext.setAttribute("count", 1);
        }else {
            Integer c = (Integer) count;
            servletContext.setAttribute("count", -- c );
        }
    }
}
